package com.forester.foresterplatform.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.forester.foresterplatform.common.utils.MyBatisPlusUtils;
import com.forester.foresterplatform.system.mapper.UserMapper;
import com.forester.foresterplatform.system.entity.User;
import com.forester.foresterplatform.system.exception.ForesterException;
import com.forester.foresterplatform.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(authenticationToken); // 认证成功后获得写入权限的 authentication
        } catch (Exception e) {
            throw new ForesterException("用户名 或 密码错误", e);
        }
    }

    @Override
    public boolean save(User entity) {
        // 保存用户时, 将用户密码进行加密存储
        String password = bCryptPasswordEncoder.encode(entity.getPassword());
        entity.setPassword(password);
        return super.save(entity);
    }
}
